package com.nian.global.utils;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.BaseFont;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.*;

/**
 * Created by nian on 2020/11/6.
 */
public final class PdfUtils {
    private static final Logger LOG = LoggerFactory.getLogger(PdfUtils.class.getName());

    private static String imagePath = null;

    private static String pdfFontAbsolutePath = null;

    /**
     * constructor
     */
    private PdfUtils() {

    }

    /**
     * 将HTML转换为PDF文件，支持水印
     *
     * @param htmlStr HTML内容
     * @param out     PDF文件输出流
     * @throws ParserConfigurationException 异常
     * @throws IOException                  异常
     * @throws SAXException                 异常
     * @throws DocumentException            异常
     */
    public static void generate(String htmlStr, OutputStream out) throws ParserConfigurationException, IOException, SAXException, DocumentException, com.lowagie.text.DocumentException {
        LOG.info("生成pdf开始...");
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document doc = builder.parse(new ByteArrayInputStream(htmlStr.getBytes("UTF-8")));
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(doc, null);
        // 解决中文处理
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(pdfFontAbsolutePath.split("\\|")[0], BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        fontResolver.addFont(pdfFontAbsolutePath.split("\\|")[1], BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        // 解决图片的相对路径问题
        LOG.info("图片baseURL:");
        // 目前只有水印需要此值
        renderer.getSharedContext().setBaseURL(imagePath);
        renderer.layout();
        renderer.createPDF(out);

        LOG.info("生成pdf完成...");

    }

    /**
     * 将字体文件从类路径复制到一个临时文件路径，并且返回这个文件路径。
     *
     * @param pdfFontPath pdf路径
     */
    public static void copyFontFile(String pdfFontPath) {
        /*String fontTempPath = System.getProperty("user.home");
        String fontTempPath1 = fontTempPath + (File.separator + "msyh.ttf");
        String fontTempPath2 = fontTempPath + (File.separator + "msyhbd.ttf");

        InputStream inputStream1 = PdfUtils.class.getClassLoader().getResourceAsStream((pdfFontPath.split("\\|")[0]).split(",")[0]);
        InputStream inputStream2 = PdfUtils.class.getClassLoader().getResourceAsStream((pdfFontPath.split("\\|")[1]).split(",")[0]);
        try {
            IOUtils.copy(inputStream1, new File(fontTempPath1));
            IOUtils.copy(inputStream2, new File(fontTempPath2));
        }
        catch (IOException e) {
            LOG.error("字体文件复制异常：" + e.getMessage(), e);
        }
        finally {
            IOUtils.closeInputStream(inputStream1);
            IOUtils.closeInputStream(inputStream2);
        }
        pdfFontAbsolutePath = fontTempPath1 + "|" + fontTempPath2;*/

        String fontTempPath = System.getProperty("user.home");
        fontTempPath += (File.separator + "simsun.ttc");

        InputStream inputStream = PdfUtils.class.getClassLoader().getResourceAsStream(pdfFontPath.split(",")[0]);

        try {
            IOUtils.copy(inputStream, new File(fontTempPath));
        } catch (IOException e) {
            LOG.error("字体文件复制异常：" + e.getMessage(), e);
        } finally {
            IOUtils.closeInputStream(inputStream);
        }
        pdfFontAbsolutePath = fontTempPath + ",0";
    }

    /**
     * 复制图片
     *
     * @param pdfImagePath pdf图片路径
     * @param pdfImagName  pdf图片名称
     */
    public static void copyImage(String pdfImagePath, String pdfImagName) {
        String targetPath = System.getProperty("user.home");
        InputStream inputStream = PdfUtils.class.getClassLoader().getResourceAsStream(pdfImagePath + pdfImagName);
        try {
            IOUtils.copy(inputStream, new File(targetPath + File.separator + pdfImagName));
        }
        catch (IOException e) {
            LOG.error("模板图片复制异常：" + e.getMessage(), e);
        }
        imagePath = "file:///" + targetPath + File.separator;
    }
}
